#!perl -w

# Copyright (c) 2009 Symbian Foundation Ltd
# This component and the accompanying materials are made available
# under the terms of the License "Eclipse Public License v1.0"
# which accompanies this distribution, and is available
# at the URL "http://www.eclipse.org/legal/epl-v10.html".
#
# Initial Contributors:
# Symbian Foundation Ltd - initial contribution.
# 
# Contributors:
#
# Description: bzcsv2mw.pl - simple script for converting CSV report files from Bugzilla to MediaWiKi text files
#

use strict;
use warnings;
use Text::CSV;
use Getopt::Long;

sub Usage($)
  {
  my ($msg) = @_;
  
  print "$msg\n\n" if ($msg ne "");
  
	print <<'EOF';
    
  bzcsv2mw.pl - simple script for converting CSV report files from Bugzilla to MediaWiki text files

  Options:

  -csv 			CSV file generated by Bugzilla
  -h|-help		print this help information

EOF
  exit (1);  
  }

my $file = "";
my $help = 0;
my $count_nb_total_bugs=0;

if (!GetOptions(
    "csv=s" => \$file,
   	"h|help" => \$help,
    ))
  {
  Usage("Invalid argument");
  }

Usage("Too few arguments....use -csv") if ($file eq "");
Usage("") if ($help); 

#my $file = $ARGV[0];
my $csv = Text::CSV->new();
my $mwtxt = $file.".mw.txt";

open (CSV, "<", $file) or die $!;
open (MWTXT,">$mwtxt");
print MWTXT "{|\n";

my %headermap = ("bug_id"=>"ID","bug_severity"=>"Severity","reporter"=>"Reporter","bug_status"=>"Status","product"=>"Package",
				"short_desc"=>"Title","priority"=>"Priority","assigned_to"=>"Assigned To","resolution"=>"Resolution","op_sys"=>"OS",);

my $header=0;
while (<CSV>) {
	if ($csv->parse($_)) 
	{
		my @columns = $csv->fields();
		
		if(!$header)
		{	
			$header=1;
			foreach (@columns) 
			{
				#my $val = $_; 
				#if(defined $headermap{$val}){$val = $headermap{$val};}
				print MWTXT "!".$headermap{$_}."\n";
			}			
		}
		else
		{
			if ($columns[0] =~ m/(\d+)/)
			{
				$columns[0] = "[http://developer.symbian.org/bugs/show_bug.cgi?id=$columns[0] Bug$columns[0]]";
			}		
			foreach (@columns) 
			{
				print MWTXT "|$_\n";
			}
			$count_nb_total_bugs++;
		}
	} 
	else 
	{
		my $err = $csv->error_input;
		print "Failed to parse line: $err";
	}
	
	print MWTXT "|----\n";
}

close CSV;
print MWTXT "|}\n";
close MWTXT;
print "\nThe number of bugs is: $count_nb_total_bugs\n";
